#include "timer.h"
#include "utility.h"

//Timer implementation
Timer::Timer(double timerLength) : idComponent(NULL, "id")
{
    //Initialize the variables
    paused = false; //Not paused
	repeat = false; //Not repeating
	inactive = false; //Not done
    time = 0.0; //No time on the clock
	timeSpan = timerLength;
	callback = NULL;
	callbackParam = NULL;
	repeatCount = 0;
	repeatTarget = 0;
}

Timer::~Timer()
{
	log_info(std::string("~Timer() id: ") + idComponent.id);
}

void Timer::start()
{
    paused = false; //Not paused
	inactive = false; //Not inactive anymore
	time = 0.0; //reset time
}

void Timer::stop()
{
    //Stop the timer
    inactive = true;
    //Unpause the timer
    paused = false;    
}

double Timer::get_time()
{
    return time;    
}

void Timer::set_callback(TimerCallback cb, void* cbParam)
{
	callback = cb;
	callbackParam = cbParam;
}

TimerCallback Timer::get_callback()
{
	return callback;
}

void Timer::set_repeat(bool rpt)
{
	repeat = rpt;
}

bool Timer::get_repeat()
{
	return repeat;
}

void Timer::set_timespan(double span)
{
	timeSpan = span;
}

double Timer::get_timespan()
{
	return timeSpan;
}

void Timer::update(double timeDelta)
{
	if (!inactive && !paused)
	{
		time += timeDelta;

		if (timeSpan > 0 && time >= timeSpan)
		{
			if (callback != NULL)
				(*callback)(callbackParam, this); //Call on callback function

			if (!repeat)
			{
				inactive = true;
			}
			else //If repeating, reset timer
			{
				//Wind back to normal range, preserving how much over the interval we were
				while (time >= timeSpan)
					time -= timeSpan;
			}
		}
	}
}

void Timer::pause()
{
    //If the timer is running and isn't already paused
    if( ( inactive == false ) && ( paused == false ) )
    {
        //Pause the timer
        paused = true;
    
        //Calculate the paused ticks
        //pausedTicks = SDL_GetTicks() - startTicks;
    }
}

void Timer::unpause()
{
    //If the timer is paused
    if( paused == true )
    {
        //Unpause the timer
        paused = false;
    
        //Reset the starting ticks
        //startTicks = SDL_GetTicks() - pausedTicks;
        
        //Reset the paused ticks
        //pausedTicks = 0;
    }
}

bool Timer::is_inactive()
{
    return inactive;
}

bool Timer::is_paused()
{
    return paused;    
}